﻿//============================================================
//write by bxl at 2021-06-13 22:03:22
//============================================================



using System.Collections.Generic;
using System;
using BCService.Utils;
using BCCommon;
using BCData.CRM.BigCustomer;
using BCDto.CRM.BigCustomer;
using BCEntity.CRM.BigCustomer;
using BCDto.Sim.Admin.Admin;
using BCEntity.Common.EntityNameConst;
using BCService.MapperProfiles.TMS.SpecificServiceType;
using BCDto.TMS.SpecificServiceType;

namespace BCService.CRM.BigCustomer
{
    public class BigCustomerService : IBigCustomerService
    {
        #region var
        private readonly IDatabaseContext databaseContext;
        private IBigCustomerData bigCustomerData;
        private readonly IRedisService redisService;

        private readonly string key = string.Format("{0}", EntityNameConst.BigCustomerEntity);

        #endregion

        #region 构造函数
        public BigCustomerService(IBigCustomerData bigCustomerData, IDatabaseContext databaseContext, IRedisService redisService)
        {
            this.bigCustomerData = bigCustomerData;
            this.databaseContext = databaseContext;
            this.redisService = redisService;
        }
        #endregion

        #region Add
        /// <returns></returns>
        public BigCustomerDto Add(BigCustomerRequestDto bigCustomerRequestDto, AdminDto admin)
        {
            if (bigCustomerRequestDto.UserId.HasValue || bigCustomerRequestDto.CustomerInfoId.HasValue)
            {
                var entity = bigCustomerRequestDto.As<BigCustomerEntity>();


                entity.CompanyId = admin.CompanyId;

                entity.CreateAdminId = admin.AdminId;
                entity.CreateAdminName = admin.FullName;
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = DateTime.Now;

                return bigCustomerData.InsertAsync(entity).GetAwaiter().GetResult().As<BigCustomerDto>();
            }
            else
            {
                throw new ArgumentException("用户Id或客户信息Id必须传入一个!");
            }
        }
        #endregion

        #region update
        public BigCustomerDto Update(BigCustomerPutDto bigCustomerPutDto, AdminDto admin)
        {
            var entity = bigCustomerData.GetEntityAsync(bigCustomerPutDto.BigCustomerId).GetAwaiter().GetResult() ?? throw new ArgumentNullException("找不到要修改的记录!");
             
            if(bigCustomerPutDto.BigCustomerLevel.HasValue)
                entity.BigCustomerLevel = bigCustomerPutDto.BigCustomerLevel.Value;
            if (bigCustomerPutDto.BigCustomerGroupId.HasValue)
                entity.BigCustomerGroupId = bigCustomerPutDto.BigCustomerGroupId.Value;
            if (bigCustomerPutDto.CustomerInfoId.HasValue)
                entity.CustomerInfoId = bigCustomerPutDto.CustomerInfoId.Value;
            if (bigCustomerPutDto.UserId.HasValue)
                entity.UserId = bigCustomerPutDto.UserId.Value;
            if (bigCustomerPutDto.IsFristAssign.HasValue)
                entity.IsFristAssign = bigCustomerPutDto.IsFristAssign.Value;

            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;


            this.redisService.DeleteMultipleKey(key, false);
            return bigCustomerData.UpdateAsync(entity).GetAwaiter().GetResult().As<BigCustomerDto>();

        }
        #endregion

        #region 启用禁用业务类型
        public BigCustomerDto UpdateEnableBusinessType(BigCustomerEnableBusinessTypePutDto bigCustomerEnableBusinessTypePutDto, AdminDto admin)
        {
            var entity = bigCustomerData.GetEntityAsync(bigCustomerEnableBusinessTypePutDto.BigCustomerId).GetAwaiter().GetResult() ?? throw new ArgumentNullException("找不到要修改的记录!");

            if (bigCustomerEnableBusinessTypePutDto.EnableMoveing.HasValue)
                entity.EnableMoveing = bigCustomerEnableBusinessTypePutDto.EnableMoveing.Value;
            if (bigCustomerEnableBusinessTypePutDto.EnableRunErrands.HasValue)
                entity.EnableRunErrands = bigCustomerEnableBusinessTypePutDto.EnableRunErrands.Value;
            if (bigCustomerEnableBusinessTypePutDto.EnableSameCity.HasValue)
                entity.EnableSameCity = bigCustomerEnableBusinessTypePutDto.EnableSameCity.Value;
            if (bigCustomerEnableBusinessTypePutDto.EnableSmallPieces.HasValue)
                entity.EnableSmallPieces = bigCustomerEnableBusinessTypePutDto.EnableSmallPieces.Value;

            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;

            this.redisService.DeleteMultipleKey(key, false);
            return bigCustomerData.UpdateAsync(entity).GetAwaiter().GetResult().As<BigCustomerDto>();

        }
        #endregion


        #region 设置协议价格和最大重量
        public BigCustomerDto SetAgreementPrice(long bigCustomerId, decimal? sameCityPrice, decimal? smallPiecesPrice, decimal? sameCityPriceMaxWeight,
            decimal? smallPiecesPriceMaxWeight,decimal? runErrandsPrice,decimal? runErrandsPriceMaxWeight, AdminDto admin)
        {
            var entity = bigCustomerData.GetEntityAsync(bigCustomerId).GetAwaiter().GetResult() ?? throw new ArgumentNullException("找不到要修改的记录!");
            if (sameCityPrice.HasValue && sameCityPriceMaxWeight.HasValue)
            {
                entity.SameCityPrice = sameCityPrice.Value;
                entity.SmallPiecesPriceMaxWeight = smallPiecesPriceMaxWeight.Value;
            }
            else if (smallPiecesPrice.HasValue && smallPiecesPriceMaxWeight.HasValue)
            {
                entity.SmallPiecesPrice = smallPiecesPrice.Value;
                entity.SmallPiecesPriceMaxWeight = smallPiecesPriceMaxWeight.Value;
            }
            else if (runErrandsPrice.HasValue && runErrandsPriceMaxWeight.HasValue)
            {
                entity.RunErrandsPrice = runErrandsPrice.Value;
                entity.RunErrandsPriceMaxWeight = runErrandsPriceMaxWeight.Value;
            }
            else
            {
                throw new ArgumentException("协议价格与协议价格最大重量应同时存在!");
            }

            entity.UpdateTime = DateTime.Now;
            entity.EditAdminId = admin.AdminId;
            entity.EditAdminName = admin.FullName;

            this.redisService.DeleteMultipleKey(key, false);
            return bigCustomerData.UpdateAsync(entity).GetAwaiter().GetResult().As<BigCustomerDto>();
        }
        #endregion

        #region Delete
        public void Delete(long bigCustomerId)
        {
            this.redisService.DeleteMultipleKey(key, false);
            bigCustomerData.DeleteAsync(bigCustomerId).GetAwaiter().GetResult(); 
        }
        #endregion

        #region GetByBigCustomerId
        public BigCustomerDto GetById(long bigCustomerId)
        {
            string cacheKey = this.redisService.GetKey(key, bigCustomerId);

            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var a = bigCustomerData.GetEntityAsync(bigCustomerId).GetAwaiter().GetResult();
                return a.As<BigCustomerDto>();

            }
            , TimeSpan.FromDays(1));
            return result.As<BigCustomerDto>();
        }

        public BigCustomerDto GetByUserId(long userId)
        {
            string cacheKey = this.redisService.GetKey(key, userId);

            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var entity = bigCustomerData.GetEntityByUserIdAsync(userId).GetAwaiter().GetResult();
                return entity.As<BigCustomerDto>();

            }
            , TimeSpan.FromDays(1));
            return result.As<BigCustomerDto>();
        }
        #endregion

        #region GetList  获取大客户信息记录--[分页]
        public PageableList<BigCustomerViewDto> GetList(AdminDto admin, long? bigCustomerGroupId, int? bigCustomerLevel, string customerName, string provinceCode, string cityCode, string countyCode, string phone, string weChatNo, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            int fCount = 0;
            IEnumerable<BigCustomerViewEntity> fList;
            int? companyId = null;
            if (!admin.IsSystemAccount)
                companyId = admin.CompanyId;


            string cacheKey = this.redisService.GetKey(key, companyId, bigCustomerGroupId, bigCustomerLevel, customerName, provinceCode, cityCode, countyCode, phone, weChatNo, start, end, pageIndex, pageSize);

            var result = this.redisService.TryGet(cacheKey, () =>
            {
                (fList, fCount) = bigCustomerData.GetListAsync(companyId, null, bigCustomerGroupId, bigCustomerLevel, customerName, provinceCode, cityCode, countyCode, phone, weChatNo, start, end, pageIndex, pageSize).GetAwaiter().GetResult();

                return new PageableList<BigCustomerViewDto>()
                {
                    Count = fCount,
                    Items = fList.As<IEnumerable<BigCustomerViewDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion
    }
}